package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 92. 翻转链表 II
 * @date 2025/5/19 11:35
 */
public class E92 {
    public ListNode reverseBetween1(ListNode head, int left, int right) {
        ListNode sentinel, tail, s = new ListNode(), curr = s;
        s.next = head;
        if (left == right) return s.next;
        int count = 0;
        while (curr != null) {
            if (count == left - 1) {
                sentinel = curr;
                tail = curr.next;
                curr = curr.next;
                count++;
                while (count < right) {
                    ListNode temp = curr.next;
                    curr.next = sentinel.next;
                    sentinel.next = curr;
                    curr = temp;
                    count++;
                }
                tail.next = curr.next;
                curr.next = sentinel.next;
                sentinel.next = curr;
                break;
            }
            curr = curr.next;
            count++;
        }
        return s.next;
    }

    public ListNode reverseBetween2(ListNode head, int left, int right) {
        ListNode sentinel = new ListNode(), innerSentinel, curr = sentinel, tail;
        sentinel.next = head;
        if (left == right) return sentinel.next;
        for (int i = 0; i < left - 1; i++) {
            curr = curr.next;
        }
        innerSentinel = curr;
        curr = curr.next;
        tail = curr;
        for (int i = 0; i < right - left + 1; i++) {
            ListNode temp = curr.next;
            tail.next = temp;
            curr.next = innerSentinel.next;
            innerSentinel.next = curr;
            curr = temp;
        }
        return sentinel.next;
    }
}
